class LevelsController < ApplicationController
  def index
    @ranks = Rank.find(:all,:order=>'position')
    @levels = Level.find(:all,:order=>'position')
  end
    #创建新的军衔
  def create_rank
    @rank = Rank.new(params[:item])
    @rank.position=Rank.count+1
    if @rank.save
      render :update do |page|
        page.create_succeed(:rank,@rank)
      end
    end
  end

  #给军衔排序
  def sort_ranks
    @ranks = Rank.all
    @ranks.each do |rank|
      rank.position=params['rank_list'].index(rank.id.to_s)+1
      rank.save
    end
    render :nothing=>true
  end

  #删除军衔
  def del_rank
    rank = Rank.find(params[:id])
     del(rank)
  end

  #创建新级别
  def create_level
    @level = Level.new(params[:item])
    @level.position=Level.count+1
    if @level.save
      render :update do |page|
        page.create_succeed(:level,@level)
      end
    end
  end
  #给级别排序
  def sort_levels
    @levels = Level.all
    @levels.each do |level|
      level.position=params['level_list'].index(level.id.to_s) + 1
      level.save
    end
    render :nothing=>true
  end
  
  #删除级别
  def del_level
    level = Level.find(params[:id])
     del(level)
  end

  def csv
    send_data User.report_table(:all,:only=>[:id,:name,:tel,:form]).to_csv,:type=>"application/csv",:filename=>"user.cvs"
  end

  def pdf
    send_data User.report_table(:all,:only=>[:id,:name,:tel,:form]).to_pdf,:type=>"application/pdf",:filename=>"user.pdf"
  end

private
  def del(obj)
    if obj.destroy
      render :update do |page|
        page.remove("#{obj.class.to_s.downcase}_#{obj.id}")
      end
    end
  end
end
